package com.wyh.util;

import com.wyh.filter.TimeFilter;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author wuyuhan
 * @date 2021/1/27 20:03
 */
public class Report implements Runnable {
    protected double percent90 = 0.9;  //90分位
    protected double percent99 = 0.99; //99分位

    @Override
    public void run() {
        System.out.println("开始上报...");
        HashMap<String, TreeSet<TimeFilter.ReqTime>> reqTime = TimeFilter.REQ_TIME;
        Set<Map.Entry<String, TreeSet<TimeFilter.ReqTime>>> entries = reqTime.entrySet();
        for (Map.Entry<String, TreeSet<TimeFilter.ReqTime>> entry : entries) {
            String method = entry.getKey();
            TreeSet<TimeFilter.ReqTime> value = entry.getValue();
            report(value, method);
        }
        System.out.println("==================================");
    }

    protected void report(TreeSet<TimeFilter.ReqTime> reqTimes, String method) {
        synchronized (reqTimes) {
            long currTime=System.currentTimeMillis() - 60000;
            for (TimeFilter.ReqTime reqTime : reqTimes) {
                if (reqTime.sendTime < currTime) {
                    reqTimes.remove(reqTime);
                }
            }
            int size = reqTimes.size();
            int percent90Point = (int) (size * percent90);
            int percent99Point = (int) (size * percent99);

            TimeFilter.ReqTime reqTimeTP90Data = null;
            TimeFilter.ReqTime reqTimeTP99Data = null;
            int count=1;
            for (TimeFilter.ReqTime reqTime : reqTimes) {
                if(count == percent90Point) {
                    reqTimeTP90Data = reqTime;
                } else if(count == percent99Point) {
                    reqTimeTP99Data = reqTime;
                }
                count++;
            }
            System.out.println("方法【" + method + "】最近一分钟运行结果：");
            System.out.println("  90分位点耗时：" + reqTimeTP90Data.spendTime);
            System.out.println("  99分位点耗时：" + reqTimeTP99Data.spendTime);
        }
    }
}
